<template>
	<view>
		<view class="uni-header">
			<view class="uni-group">
				<view class="uni-title"></view>
				<view class="uni-sub-title"></view>
			</view>
			<view class="uni-group">
				<input class="uni-search" type="text" v-model="query" @confirm="search" placeholder="请输入搜索内容" />
				<button class="uni-button" type="default" size="mini" @click="search">搜索</button>
				<button class="uni-button" type="default" size="mini" @click="navigateTo('./add')">新增</button>
				<button class="uni-button" type="default" size="mini" :disabled="!selectedIndexs.length"
					@click="delTable">批量删除</button>
				<download-excel class="hide-on-phone" :fields="exportExcel.fields" :data="exportExcelData"
					:type="exportExcel.type" :name="exportExcel.filename">
					<button class="uni-button" type="primary" size="mini">导出 Excel</button>
				</download-excel>
			</view>
		</view>
		<view class="uni-container">
			<unicloud-db ref="udb" :collection="collectionList"
				field="apply_status,id_front,id_back,real_name,id_number,contact_phone,contact_address,reason,audit_time,create_time,user_id.nickname as userName,user_id._id as userId"
				:where="where" page-data="replace" :orderby="orderby" :getcount="true" :page-size="options.pageSize"
				:page-current="options.pageCurrent" v-slot:default="{data,pagination,loading,error,options}"
				:options="options" loadtime="manual" @load="onqueryload">
				<uni-table ref="table" :loading="loading" :emptyText="error.message || '没有更多数据'" border stripe
					type="selection" @selection-change="selectionChange">
					<uni-tr>
						<uni-th align="center" filter-type="range" @filter-change="filterChange($event, 'apply_status')"
							sortable @sort-change="sortChange($event, 'apply_status')">申请状态</uni-th>
						<uni-th align="center" sortable @sort-change="sortChange($event, 'id_front')">身份证正面照片</uni-th>
						<uni-th align="center" sortable @sort-change="sortChange($event, 'id_back')">身份证反面照片</uni-th>
						<uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'real_name')"
							sortable @sort-change="sortChange($event, 'real_name')">真实姓名</uni-th>
						<uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'id_number')"
							sortable @sort-change="sortChange($event, 'id_number')">身份证号码</uni-th>
						<uni-th align="center" filter-type="search"
							@filter-change="filterChange($event, 'contact_phone')" sortable
							@sort-change="sortChange($event, 'contact_phone')">联系电话</uni-th>
						<uni-th align="center" filter-type="search"
							@filter-change="filterChange($event, 'contact_address')" sortable
							@sort-change="sortChange($event, 'contact_address')">联系地址</uni-th>
						<uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'reason')"
							sortable @sort-change="sortChange($event, 'reason')">申请理由</uni-th>
						<uni-th align="center" filter-type="timestamp"
							@filter-change="filterChange($event, 'audit_time')" sortable
							@sort-change="sortChange($event, 'audit_time')">审核时间</uni-th>
						<uni-th align="center" filter-type="timestamp"
							@filter-change="filterChange($event, 'create_time')" sortable
							@sort-change="sortChange($event, 'create_time')">创建时间</uni-th>
						<uni-th align="center" sortable @sort-change="sortChange($event, 'user_id')">申请用户</uni-th>
						<uni-th align="center">操作</uni-th>
					</uni-tr>
					<uni-tr v-for="(item,index) in data" :key="index">
						<uni-td align="center">
							<view class="ping-13-25"
								:class="item.apply_status == 0?'bac-col-4e col-f':item.apply_status==1?'bac-col-00b col-f':'col-87 bac-col-fa'">
								{{item.apply_status==0?'审核中':item.apply_status==1?'审核通过':'拒绝申请'}}
							</view>
						</uni-td>
						<uni-td align="center">
							<image @click="$PreviewImg([item.id_front[0].url])" :src="item.id_front[0].url"
								style="width: 240rpx;height: 150rpx;"></image>
						</uni-td>
						<uni-td align="center">
							<image @click="$PreviewImg([item.id_back[0].url])" :src="item.id_back[0].url"
								style="width: 240rpx;height: 150rpx;"></image>
						</uni-td>
						<uni-td align="center">{{item.real_name}}</uni-td>
						<uni-td align="center">{{item.id_number}}</uni-td>
						<uni-td align="center">{{item.contact_phone}}</uni-td>
						<uni-td align="center">{{item.contact_address}}</uni-td>
						<uni-td align="center">{{item.reason}}</uni-td>
						<uni-td align="center">
							<uni-dateformat :threshold="[0, 0]" :date="item.audit_time"></uni-dateformat>
						</uni-td>
						<uni-td align="center">
							<uni-dateformat :threshold="[0, 0]" :date="item.create_time"></uni-dateformat>
						</uni-td>
						<uni-td align="center">{{item.userName[0] || '-'}}</uni-td>
						<uni-td align="center">
							<view class="uni-group">
								<button v-if="item.apply_status == 0" @click="toExamine(item)" class="uni-button"
									size="mini" type="primary">审核</button>
								<button v-if="item.apply_status == 1" @click="removeRole(item)" class="uni-button"
									size="mini" type="warn">移除组织者权限</button>
								<button @click="toExamine(item)" class="uni-button" size="mini"
									type="default">查看</button>
							</view>
						</uni-td>
					</uni-tr>
				</uni-table>
				<view class="uni-pagination-box">
					<uni-pagination show-icon :page-size="pagination.size" v-model="pagination.current"
						:total="pagination.count" @change="onPageChanged" />
				</view>
			</unicloud-db>
		</view>
		<!-- 审核弹窗 -->
		<view>
			<uni-drawer ref="showRight" mode="right" :width="drawerWidth">
				<view class="ping-40">
					<view class="w-100 flex-dir-row ali-item-cen bor-bottom-f3 pb-40" style="align-items: stretch;">
						<view class="shu"></view>
						<view class="fs-32 fw-900 ml-10">认证审核</view>
					</view>
					<view class="pt-40">
						<view class="flex-dir-row ali-item-cen  mb-40">
							<view class="fs-30 fw-600">申请用户：</view>
							<view class="fs-30">
								{{examineData.userName && examineData.userName.length?examineData.userName[0]: '-'}}
							</view>
						</view>
						<view class="flex-dir-row ali-item-cen  mb-40">
							<view class="fs-30 fw-600">用户ID：</view>
							<view class="fs-30">
								{{examineData.userId && examineData.userId.length?examineData.userId[0]: '-'}}
							</view>
						</view>
						<view class="flex-dir-row ali-item-cen mb-40">
							<view class="fs-30 fw-600">审核状态：</view>
							<view class="fs-30 ping-15-80"
								:class="examineData.apply_status == 0?'bac-col-4e col-f':examineData.apply_status==1?'bac-col-00b col-f':'col-87 bac-col-fa'">
								{{examineData.apply_status==0?'审核中':examineData.apply_status==1?'审核通过':'拒绝申请'}}
							</view>
						</view>
						<view class="flex-dir-row ali-item-cen mb-40">
							<view class="fs-30 fw-600">证件照片：</view>
							<view class="flex-dir-row ali-item-cen">
								<image
									@click="$PreviewImg([examineData.id_front&&examineData.id_front.length?examineData.id_front[0].url:''])"
									:src="examineData.id_front&&examineData.id_front.length?examineData.id_front[0].url:''"
									style="width: 240rpx;height: 150rpx;" class="mr-40"></image>
								<image
									@click="$PreviewImg([examineData.id_back&&examineData.id_back.length?examineData.id_back[0].url:''])"
									:src="examineData.id_back&&examineData.id_back.length?examineData.id_back[0].url:''"
									style="width: 240rpx;height: 150rpx;"></image>
							</view>
						</view>
						<view class="flex-dir-row ali-item-cen mb-40">
							<view class="fs-30 fw-600">真实姓名：</view>
							<view class="fs-30">
								{{examineData.real_name}}
							</view>
						</view>
						<view class="flex-dir-row ali-item-cen mb-40">
							<view class="fs-30 fw-600">身份证号：</view>
							<view class="fs-30">
								{{examineData.id_number}}
							</view>
						</view>
						<view class="flex-dir-row ali-item-cen mb-40">
							<view class="fs-30 fw-600">联系电话：</view>
							<view class="fs-30">
								{{examineData.contact_phone}}
							</view>
						</view>
						<view class="flex-dir-row ali-item-cen mb-40">
							<view class="fs-30 fw-600">联系地址：</view>
							<view class="fs-30">
								{{examineData.contact_address}}
							</view>
						</view>
						<view class="flex-dir-row ali-item-cen">
							<view class="fs-30 fw-600">申请理由：</view>
							<view class="fs-30">
								{{examineData.reason}}
							</view>
						</view>
					</view>
					<!-- 审核按钮 -->
					<view v-if="examineData.apply_status == 0" class="flex-dir-row ali-item-cen flex-x-spa mt-40">
						<button style="width: 300rpx;height: 80rpx;line-height: 80rpx;" type="primary" size="mini"
							@click="examine(1)">审核通过</button>
						<button style="width: 300rpx;height: 80rpx;line-height: 80rpx;" type="warn" size="mini"
							@click="examine(2)">拒绝申请</button>
					</view>
				</view>
			</uni-drawer>
		</view>
		<!-- 拒绝原因弹窗 -->
		<uni-popup ref="popupState" type="dialog">
			<uni-popup-dialog mode="input" v-model="refuseReason" title="拒绝原因" placeholder="请输入您拒绝的原因"
				@confirm="examine(2)" @close="refuseReason=''">
			</uni-popup-dialog>
		</uni-popup>
		<!-- 移除组织者角色弹窗 -->
		<uni-popup ref="removeRolePopup" type="dialog">
			<uni-popup-dialog mode="input" v-model="removeRoleReason" title="移除原因" placeholder="请输入您移除的原因"
				@confirm="removeRole('')" @close="removeRoleReason=''">
			</uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	import {
		enumConverter,
		filterToWhere
	} from '../../js_sdk/validator/qmy-certification-application.js';

	const db = uniCloud.database()
	// 表查询配置
	const dbOrderBy = '' // 排序字段
	const dbSearchFields = ['user_id.nickname',
		'real_name'] // 模糊搜索字段，支持模糊搜索的字段列表。联表查询格式: 主表字段名.副表字段名，例如用户表关联角色表 role.role_name
	// 分页配置
	const pageSize = 20
	const pageCurrent = 1

	const orderByMapping = {
		"ascending": "asc",
		"descending": "desc"
	}

	export default {
		data() {
			return {
				collectionList: "qmy-certification-application,uni-id-users",
				query: '',
				where: '',
				orderby: dbOrderBy,
				orderByFieldName: "",
				selectedIndexs: [],
				options: {
					pageSize,
					pageCurrent,
					filterData: {},
					...enumConverter
				},
				imageStyles: {
					width: 64,
					height: 64
				},
				exportExcel: {
					"filename": "qmy-certification-application.xls",
					"type": "xls",
					"fields": {
						"申请状态": "apply_status",
						"身份证正面照片": "id_front",
						"身份证反面照片": "id_back",
						"真实姓名": "real_name",
						"身份证号码": "id_number",
						"联系电话": "contact_phone",
						"联系地址": "contact_address",
						"申请理由": "reason",
						"审核时间": "audit_time",
						"创建时间": "create_time",
						"user_id": "user_id"
					}
				},
				exportExcelData: [],
				examineData: {},
				drawerWidth: 500,
				refuseReason: '',
				removeRoleReason: ''
			}
		},
		onLoad() {
			this._filter = {}
		},
		onReady() {
			this.$refs.udb.loadData()
		},
		methods: {
			// 审核/查看
			toExamine(data) {
				this.$refs.showRight.open();
				this.examineData = data;
			},
			// 审核
			async examine(status) {
				if (status == 2 && !this.refuseReason) {
					this.$refs.popupState.open();
					uni.showToast({
						title: '请输入拒绝原因',
						icon: 'none'
					})
					return;
				}
				uni.showLoading({
					title: '审核中...',
					mask: true
				});
				await db.collection('qmy-certification-application').doc(this.examineData._id).update({
					apply_status: status,
					audit_time: Date.now()
				}).then(async (res) => {
					await this.sendNotice(status);
					// 给用户加上组织者角色
					if (status == 1) {
						await this.addRole(this.examineData.userId[0]);
					}
					uni.showToast({
						title: '审核成功',
						icon: 'none'
					})
					this.$refs.showRight.close();
					this.$nextTick(() => {
						this.loadData()
					})
				}).catch(err => {
					uni.showToast({
						title: '审核失败,' + err.errMsg,
						icon: 'none'
					})
				})
			},
			// 发送通知
			async sendNotice(status) {
				// 给用户发送审核结果通知
				await db.collection('qmy-notice').add({
					receive_user_id: this.examineData.userId[0],
					notice_type: 0,
					system_notice_type: '组织认证审核结果通知',
					notice_title: status == 1 ? '您的认证申请已通过审核' : status == 2 ? '您的认证申请已被拒绝' : '您的组织者权限已被移除',
					notice_content: status == 1 ?
						'我们认真审核了您的认证信息，恭喜您成功通过审核！您现在可以发布并组织活动、发送活动通知给报名您活动的用户，快去试试吧！' : status == 2 ? this
						.refuseReason : this.removeRoleReason,
					user_read_status: 0,
				}).then().catch(err => {
					uni.showToast({
						title: '通知发送失败,' + err.errMsg,
						icon: 'none'
					})
				})
				this.refuseReason = '';
			},
			// 给用户加上组织者角色
			async addRole(userId) {
				// 先查询用户拥有的角色
				await db.collection('uni-id-users').doc(userId).field('role').get().then(async (res) => {
					console.log(res);
					let role = res.result.data[0]?.role || [];
					if (!role.includes('organizer')) {
						role.push('organizer');
					}
					await db.collection('uni-id-users').doc(userId).update({
						role: role
					}).then().catch(err => {
						uni.showToast({
							title: '给用户加上组织者角色失败,失败原因：' + err.errMsg +
								'，请前往用户管理手动给用户加上组织者角色',
							icon: 'none',
							duration: 5000
						})
					})
				}).catch(err => {
					uni.showToast({
						title: '给用户加上组织者角色失败,失败原因：' + err.errMsg + '，请前往用户管理手动给用户加上组织者角色',
						icon: 'none',
						duration: 5000
					})
				})
			},
			// 移除用户组织者角色
			async removeRole(data) {
				if (data) {
					this.examineData = data;
				}
				if (!this.removeRoleReason) {
					this.$refs.removeRolePopup.open();
					uni.showToast({
						title: '请输入移除原因',
						icon: 'none'
					})
					return;
				}
				uni.showLoading({
					title: '移除中...',
					mask: true
				});
				// 先查询用户拥有的角色
				await db.collection('uni-id-users').doc(this.examineData.userId[0]).field('role').get().then(async (
					res) => {
					let role = res.result.data[0]?.role || [];
					if (role.includes('organizer')) {
						role.splice(role.indexOf('organizer'), 1);
					}
					await db.collection('uni-id-users').doc(this.examineData.userId[0]).update({
						role: role
					}).then(async () => {
						this.removeRoleReason = '';
						// 删除此条申请记录
						await db.collection('qmy-certification-application').doc(this
							.examineData._id).remove();
						uni.showToast({
							title: '移除角色成功',
							icon: 'none'
						})
						setTimeout(() => {
							this.$nextTick(() => {
								this.loadData()
							})
						}, 1600);
						// 发送移除组织者角色通知
						this.sendNotice(3);
					}).catch(err => {
						uni.showToast({
							title: '移除用户组织者角色失败,失败原因：' + err.errMsg,
							icon: 'none'
						})
					})
				}).catch(err => {
					uni.showToast({
						title: '移除用户组织者角色失败,失败原因：' + err.errMsg,
						icon: 'none'
					})
				})
			},
			onqueryload(data) {
				this.exportExcelData = data
			},
			getWhere() {
				const query = this.query.trim()
				if (!query) {
					return ''
				}
				const queryRe = new RegExp(query, 'i')
				return dbSearchFields.map(name => queryRe + '.test(' + name + ')').join(' || ')
			},
			search() {
				const newWhere = this.getWhere()
				this.where = newWhere
				this.$nextTick(() => {
					this.loadData()
				})
			},
			loadData(clear = true) {
				this.$refs.udb.loadData({
					clear
				})
			},
			onPageChanged(e) {
				this.selectedIndexs.length = 0
				this.$refs.table.clearSelection()
				this.$refs.udb.loadData({
					current: e.current
				})
			},
			navigateTo(url, clear) {
				// clear 表示刷新列表时是否清除页码，true 表示刷新并回到列表第 1 页，默认为 true
				uni.navigateTo({
					url,
					events: {
						refreshData: () => {
							this.loadData(clear)
						}
					}
				})
			},
			// 多选处理
			selectedItems() {
				var dataList = this.$refs.udb.dataList
				return this.selectedIndexs.map(i => dataList[i]._id)
			},
			// 批量删除
			delTable() {
				this.$refs.udb.remove(this.selectedItems(), {
					success: (res) => {
						this.$refs.table.clearSelection()
					}
				})
			},
			// 多选
			selectionChange(e) {
				this.selectedIndexs = e.detail.index
			},
			confirmDelete(id) {
				this.$refs.udb.remove(id, {
					success: (res) => {
						this.$refs.table.clearSelection()
					}
				})
			},
			sortChange(e, name) {
				this.orderByFieldName = name;
				if (e.order) {
					this.orderby = name + ' ' + orderByMapping[e.order]
				} else {
					this.orderby = ''
				}
				this.$refs.table.clearSelection()
				this.$nextTick(() => {
					this.$refs.udb.loadData()
				})
			},
			filterChange(e, name) {
				this._filter[name] = {
					type: e.filterType,
					value: e.filter
				}
				let newWhere = filterToWhere(this._filter, db.command)
				if (Object.keys(newWhere).length) {
					this.where = newWhere
				} else {
					this.where = ''
				}
				this.$nextTick(() => {
					this.$refs.udb.loadData()
				})
			}
		}
	}
</script>

<style>
</style>